<template>
	<view class="container">
		<!-- <view class="navbar">
			<button type="default" plain class="talk-btn">
				<image src="/static/images/order/order_icon_talk2.0.png"></image>
				<view>想对你说</view>
			</button>
		</view> -->
		<view class="tabbar">
			<view class="item" :class="{active: !tabIndex}" @tap="switchTab(0)">当前订单</view>
			<view class="item" :class="{active: tabIndex}" @tap="switchTab(1)">历史订单</view>
		</view>
			<swiper :current="tabIndex" :duration="300" class="swiper" :show-scrollbar="false">
				<!-- 当前订单 begin -->
				<swiper-item @touchmove.stop="handleSwiperItemChange">
					<view class="no-order-content" v-if="Object.keys(ordersnow).length <= 0">
						<view class="tips">
							<view>您今天还没有下单</view>
							<view>快去选择喜欢的菜吧</view>
						</view>
						<button type="primary" class="font-size-lg" hover-class="none">去下单</button>
					</view>	
					<view class="order-list" v-if="Object.keys(ordersnow).length > 0">
						<view class="order">
							<view class="header">
								<view class="flex-fill font-size-medium">{{ "桂店花江店" }}</view>
								<view class="status">
									<view>未结算</view>
									<image src="/static/images/common/black_arrow_right.png"></image>
								</view>
							</view>
							<scroll-view scroll-x>
								<view class="images">
									<image :src="item.menuImage" v-for="(item, index) in cart" :key="index"></image>
								</view>
							</scroll-view>
							<view class="info">
								<view class="left">
									<view>订单编号：{{ ordersnow.orderNum }}</view>
									<view>下单时间：{{ formatDateTime(ordersnow.orderTimestart) }}</view>
								</view>
								<view class="right">
									￥{{ amountToShowInTemplate }}
								</view>
							</view>
							<view class="action">
								<button type="default" hover-class="none"
									@click="navigateToOrderDetail(ordersnow.orderId)">查看订单</button>
								<button type="default" hover-class="none" @click="addmenu()">加菜</button>
								<button type="primary" plain hover-class="none" @click="pay()">结算</button>
							</view>
						</view>
					</view>
				</swiper-item>
				<!-- 当前订单 end -->
				<!-- 历史订单 begin -->
				<swiper-item @touchmove.stop="handleSwiperItemChange">
					<view class="history-order">
						<view class="menu">
							<view class="flex-fill d-flex justify-content-start">
								<view class="item" :class="{active: !orderMenuIndex}" @tap="switchMenuTab(0)">门店订单
								</view>
								<view class="item" :class="{active: orderMenuIndex}" @tap="switchMenuTab(1)">百货订单</view>
							</view>
							<!-- 					<view class="item" v-show="batchInvoiceVisible">
							<image src="/static/images/order/batch_invoice_icon.png"></image>
							<view>批量开票</view>
						</view> -->
						</view>
						<swiper :current="orderMenuIndex" :duration="300" :show-scrollbar="false"
							class="history-order-swiper">
							<!-- 门店订单 begin -->
							<swiper-item @touchmove.stop="handleSwiperItemChange">
								<scroll-view scroll-y="true" class="orders-scroll">
									<view class="wrapper">
										<view class="order-list">
											<navigator class="order" v-for="(order, index) in orders" :key="index"
												open-type="navigate" @click="navigateToOrderDetail(order.orderId)">
												<view class="header">
													<view class="flex-fill font-size-medium">{{ "桂店花江店" }}</view>
													<view class="status">
														<view>已完成</view>
														<image src="/static/images/common/black_arrow_right.png">
														</image>
													</view>
												</view>
												<scroll-view scroll-x>
													<view class="images">
														<image :src="items.menuImage"
															v-for="(items, index) in order.menuItem" :key="index">
														</image>
													</view>
												</scroll-view>
												<view class="info">
													<view class="left">
														<view>订单编号：{{ order.orderNum }}</view>
														<view>下单时间：{{ formatDateTime(order.orderTimestart) }}</view>
													</view>
													<view class="right">
														￥{{ order.orderCost }}
													</view>
												</view>
												<view class="action">
													<button type="default" hover-class="none">开发票</button>
													<button type="default" hover-class="none">查看评论</button>
													<button type="primary" plain hover-class="none">再来一单</button>
												</view>
											</navigator>
										</view>
									</view>
								</scroll-view>
							</swiper-item>
							<!-- 门店订单 end -->
							<!-- 百货订单 begin -->
							<swiper-item @touchmove.stop="handleSwiperItemChange">
								<view class="store-order-wrapper">
									<image src="/static/images/order/default_img_order.png"></image>
									<view>您还没有下单</view>
									<view>快去百货商城逛逛吧</view>
								</view>
							</swiper-item>
							<!-- 百货订单 end -->
						</swiper>
					</view>
				</swiper-item>
				<!-- 历史订单 end -->
			</swiper>
		<!-- <image src="https://go.cdn.heytea.com/storage/ad/2020/05/20/1a389117c2fb44d5bcad4a910a68246c.jpg"></image> -->
	</view>
</template>

<script>
	import {
		requst_get_orderInfoByorderId,
		requst_post_Settlebills,
		requst_get_customerInfo,
		requst_get_orderInfoByCustomerId,
		requst_get_menuorder,
		requst_get_orderInfoBycustomerIdNo,
		requst_put_Foodtableupdata
	} from '@/api/menu.js'
	export default {
		data() {
			return {
				tabIndex: 0,
				orderMenuIndex: 0,
				amountToShowInTemplate: 0,
				orders: {},
				order: {
					Items: [] // Initialize as an empty array
				},
				Foodtableupdata:{},
				ordersmenu: [],
				storeOrders: [],
				customerid: "",
				ordersnow: [],
				noworderId: uni.getStorageSync('noworderId'),
				cart: [],
				cartadd: uni.getStorageSync('cartadd'),
			}
		},
		async onLoad() {
			this.getOrders()
		},
		created() {
			this.getOrdersnow();
		},
		computed: {
			// batchInvoiceVisible() {
			// 	return (!this.orderMenuIndex && this.orders.length) || (this.orderMenuIndex && this.storeOrders.length)
			// },
		},
		methods: {
			onShow() {
				this.cart = uni.getStorageSync('cart')
				if (this.cart) {
					const amount = this.cartAmount();
					console.log('Cart Amount:', amount);
					// 可以将计算结果保存到数据中，以便在模板中显示
					this.amountToShowInTemplate = amount;
				}
			},
			cartAmount() {
				if (this.cart !== null) {
					return this.cart.reduce((acc, cur) => acc + cur.menuNumber * cur.menuPrice, 0)
				} else {
					return 0
				}
			},
			formatDateTime(time) {
				const options = {
					year: 'numeric',
					month: '2-digit',
					day: '2-digit',
					hour: '2-digit',
					minute: '2-digit',
					second: '2-digit',
					hour12: false,
				};

				const formattedDateTime = new Date(time).toLocaleString(undefined, options);
				return formattedDateTime;
			},
			mergeOrdersWithMenu(orders, ordersmenu) {
				return orders.map(order => {
					const matchingOrderMenu = ordersmenu.find(ordermenu => ordermenu.orderId === order.orderId);
					return {
						...order,
						Items: matchingOrderMenu ? matchingOrderMenu : []
					};
				});
			},
			async switchTab(index) {
				if (this.tabIndex === index) return
				this.tabIndex = index
				// if (this.tabIndex) {
				// 	 this.getOrders()
				// }
				// if (this.tabIndex === 0) {
				// 	await this.getOrdersnow()
				// }
			},
			handleSwiperItemChange() { //禁止手动滑动
				return true
			},
			async switchMenuTab(index) {
				if (this.orderMenuIndex === index) return
				this.orderMenuIndex = index
				// this.getOrders()
			},
			addmenu() {
				uni.navigateTo({
					url: '/pages/menu/menuadd'
				})
			},
			getOrdersnow() {
				
				if (uni.getStorageSync("noworderId")) {
					requst_get_orderInfoByorderId(this.noworderId).then(resorderno => {
						if (resorderno.data.code == 200) {
							this.ordersnow = resorderno.data.data
							requst_get_menuorder(this.noworderId).then(resmenuorder => {
								if (resmenuorder.data.code == 200) {
									this.cart = resmenuorder.data.data
									console.log(this.cart)
									uni.setStorageSync('cart', this.cart)
								}
							})
						}
					}).catch(err => {
						console.log('requst_get_customerInfo', err)
					})
				}
			},
			// requst_get_orderInfoByorderId(orderId).then(resorderno => {
			// 	if (resorderno.data.code == 200) {
			// 		uni.setStorageSync('ordersdetail', resorderno.data.data)
			// 		requst_get_menuorder(orderId).then(resmenuorder => {
			// 			if (resmenuorder.data.code == 200) {
			// 				uni.setStorageSync('ordermenudetail', resmenuorder.data.data)
			// 			}
			// 		})
			// 	}
			// }).catch(err => {
			// 	console.log('requst_get_customerInfo', err)
			// })
			navigateToOrderDetail(orderId) {
				// 在点击时触发的事件，将订单号传递给路由或者其他需要的地方
				console.log('Clicked on order with orderId:', orderId);
				uni.navigateTo({
					url: '/pages/orders/order_details?id=' + orderId,
				})
			},
			onPullDownRefresh() {
				this.getOrders()
				this.getOrdersnow()
				setTimeout(() => {
					console.log('下拉刷新触发了');
					// 加载完成后调用完成下拉刷新的方法
					this.$refs.scrollView.finishPullDown();
				}, 1000);
			},
			finishPullDown() {
				// 完成下拉刷新的操作，通知插件或组件
				// 这里是uview-ui的示例，具体根据你使用的插件调用方式调整
				this.$refs.uuLoadMore.onRefresh();
			},
			getOrders() {
				if (uni.getStorageSync("X-Token")) {
					requst_get_customerInfo(uni.getStorageSync("X-Token")).then(rescustomer => {
						if (rescustomer.data.code === 200) {
							if (rescustomer.data.data.customerId === 0) {
								uni.showToast({
									title: '请登录账号',
									icon: 'none'
								})
							} else {
								requst_get_orderInfoByCustomerId(rescustomer.data.data.customerId).then(
									resorder => {
										console.log(rescustomer.data.data.customerId)
										if (resorder.data.code == 200) {
											for (let i = 0; i < resorder.data.data.length; i++) {
												requst_get_menuorder(resorder.data.data[i].orderId).then(
													resmenuorder => {
														if (resmenuorder.data.code == 200) {
															this.ordersmenu[i] = resmenuorder.data.data
															resorder.data.data[i].menuItem = resmenuorder
																.data.data
														}
													}).catch(err => {
													console.log('requst_get_menuorder', err)
												})
											}
											this.orders = resorder.data.data
											console.log("ordersmenu", this.ordersmenu)
											console.log("orders", this.orders)
											console.log("resorder.data.data[i].menuItem", resorder.data.data)
											const mergedOrders = this.mergeOrdersWithMenu(this.orders, this
												.ordersmenu);

											// Now 'mergedOrders' contains the merged data with 'Items' property for each order
											console.log(mergedOrders);
										}
									}).catch(err => {
									console.log('ajax_err1', err)
								})
							}
						}
					}).catch(err => {
						if (err.data.code === 0) {
							uni.showToast({
								title: '登录身份过期请重新登录',
								icon: 'none'
							})
						}
					})
				} else {
					uni.showToast({
						title: '请登录账号',
						icon: 'none'
					})
				}
			},
			pay() {
				const amount = this.cartAmount();
				uni.showModal({
					title: '订单是否结算？',
					success: function(res) {
						if (res.confirm) {
							this.Foodtableupdata = uni.getStorageSync('selectedTable')
							this.Foodtableupdata.tableCondition = 1
							console.log("sssssssss",this.Foodtableupdata)
							requst_put_Foodtableupdata(this.Foodtableupdata).then(resFoodtable => {
								if (resFoodtable.data.code == 200) {
									console.log("2121111")
								}
							}).catch(err => {
								console.log('requst_put_Foodtableupdata', err)
							})
							function getCurrentTimestamp() {
								const timestamp = Math.floor(Date.now()); // 转换为秒级时间戳
								return timestamp;
							}
							const currentTimestamp = getCurrentTimestamp();
							const Settlebillsdata = {}
							Settlebillsdata.orderId = uni.getStorageSync('noworderId')
							Settlebillsdata.orderTimefinish = currentTimestamp
							Settlebillsdata.orderCost = amount
							console.log(Settlebillsdata)
							requst_post_Settlebills(Settlebillsdata).then(res => {
								if (res.data.code === 200) {
									wx.showToast({
										title: '结算成功',
										icon: 'success',
									})
									uni.removeStorageSync('selectedTable')
									uni.removeStorageSync('cart')
									uni.removeStorageSync('noworderId')
									uni.removeStorageSync('cartadd')
								}
							})
						} else {
							console.log('点击了取消')
						}
					}
				})
			}
		},
	};
</script>

<style lang="scss" scoped>
	page {
		background-color: #f6f6f6;
	}

	// .navbar {
	// 	height: calc(44px + var(--status-bar-height));
	// 	/* #ifdef H5 */
	// 	height: 44px;
	// 	/* #endif */
	// 	display: flex;
	// 	background-color: #FFFFFF;
	// }

	.talk-btn {
		height: 32px;
		margin-left: 10px;
		margin-top: 26px;
		/* #ifdef H5 */
		margin-top: 6px;
		/* #endif */
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: $font-size-sm !important;
		padding: 0 20rpx;
		border-radius: 50rem !important;

		image {
			width: 40rpx;
			height: 40rpx;
			margin-right: $spacing-row-sm;
		}
	}

	.tabbar {
		height: 100rpx;
		background-color: $bg-color-white;
		display: flex;
		align-items: center;
		justify-content: space-around;

		.item {
			height: 100%;
			font-size: $font-size-lg;
			color: $text-color-assist;
			font-weight: 400 !important;
			display: flex;
			align-items: center;

			&.active {
				color: $text-color-base;
				border-bottom: 4rpx solid $text-color-base;
			}
		}
	}

	.swiper {
		width: 100%;
		height: 90%;
	}

	.no-order-content {
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;

		image {
			width: 300rpx;
			height: 300rpx;
			margin-bottom: 50rpx;
		}

		.tips {
			color: $text-color-assist;
			display: flex;
			flex-direction: column;
			align-items: center;
			line-height: 1.2rem !important;
			margin-bottom: 70rpx;
		}

		button {
			width: 50%;
		}
	}

	.history-order {
		width: 100%;
		height: 100%;
		position: relative;

		.menu {
			padding: 18rpx 30rpx;
			display: flex;
			align-items: center;
			font-size: $font-size-base;
			color: $text-color-grey;
			position: fixed;
			top: 0;
			left: 0;
			right: 0;
			z-index: 10;

			.item {
				padding: 14rpx 30rpx;
				display: flex;
				align-items: center;
				justify-content: center;

				image {
					width: 40rpx;
					height: 40rpx;
					margin-right: 10rpx;
				}

				&.active {
					color: $color-primary;
					background-color: $bg-color-white;
				}
			}
		}

		.history-order-swiper {
			width: 100%;
			height: 100%;
		}
	}

	.store-order-wrapper {
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		font-size: $font-size-base;
		color: $text-color-assist;
		line-height: 1.3rem !important;

		image {
			width: 400rpx;
			height: 333rpx;
			margin-bottom: 40rpx;
		}
	}

	.orders-scroll {
		width: 100%;
		height: 100%;
		padding-top: 104rpx;
	}

	.order-list {
		display: flex;
		width: 100%;
		flex-direction: column;

		.order {
			background-color: $bg-color-white;
			padding: 30rpx 40rpx;
			margin-bottom: 18rpx;

			.header {
				display: flex;
				justify-content: space-between;
				align-items: center;

				.status {
					font-size: $font-size-base;
					color: $text-color-grey;
					display: flex;
					align-items: center;

					image {
						width: 30rpx;
						height: 30rpx;
						margin-left: $spacing-row-sm;
					}
				}
			}

			.images {
				display: flex;
				padding: 30rpx 0;

				image {
					flex-shrink: 0;
					width: 150rpx;
					margin-right: 3px;
					height: 112.5rpx;
				}
			}

			.info {
				display: flex;
				align-items: center;
				margin-bottom: 30rpx;

				.left {
					flex: 1;
					display: flex;
					flex-direction: column;
					font-size: $font-size-base;
					color: $text-color-grey;
				}

				.right {
					font-size: $font-size-lg;
					color: $text-color-base;
				}
			}

			.action {
				display: flex;
				justify-content: flex-end;
				align-items: center;

				button {
					margin-left: 30rpx;
					font-size: $font-size-sm;
				}
			}
		}
	}
</style>